package com.boss.salary.controller;

import com.boss.api.dto.ApiResultDTO;
import com.boss.common.base.BasicinfoBaseController;
import com.boss.common.entity.PageDTO;
import com.boss.common.util.PageUtils;
import com.boss.framework.dto.PaginationDTO;
import com.boss.salary.entity.DepartmentInfo;
import com.boss.salary.entity.OperrateLogs;
import com.boss.salary.service.IDepartmentInfoService;
import com.boss.salary.service.IOperrateLogsService;
import com.boss.sys.ca.user.dto.UserDTO;
import org.apache.commons.lang.StringUtils;
import org.apache.servicecomb.provider.rest.common.RestSchema;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestSchema(schemaId = "DepartmentInfoController")
@RestController
public class DepartmentInfoController extends BasicinfoBaseController {
    /**
     * 引入日志框架常量
     */
    private final static Logger logger = LoggerFactory.getLogger(DepartmentInfoController.class);

    @Autowired
    private IDepartmentInfoService departmentInfoService;

    @Autowired
    private IOperrateLogsService iOperrateLogsService;


    /**
     * 新增
     * @param departmentInfo
     * @return
     */
    @PostMapping("/saveDepartmentInfo")
    public ApiResultDTO saveDepartmentInfo(@RequestHeader("tokenid") String tokenid,
                                           @RequestBody DepartmentInfo departmentInfo){
        try {
            UserDTO userDTO = getUser(tokenid);
            //添加操作日志
            OperrateLogs operrateLogs= new OperrateLogs();
            operrateLogs.setMofDivCode(userDTO.getProvince());
            operrateLogs.setTokenId(tokenid);
            operrateLogs.setUserAgencyId(userDTO.getAgency());
            operrateLogs.setUeserName(userDTO.getName());
            operrateLogs.setOperateName("单位信息编辑--内部机构维护--新增科室");
            operrateLogs.setAgencyId(departmentInfo.getAgencyId());
            iOperrateLogsService.saveOperrateLogs(operrateLogs);

            departmentInfo.setMofDivCode(userDTO.getProvince());
            String restlt=departmentInfoService.insertDepartmentInfo(departmentInfo);
            return ApiResultDTO.success(restlt, "保存成功");
        } catch (Exception e) {
            logger.error("新增 组织机构内部门表发生异常", e);
            return ApiResultDTO.error(ERROR_RSCODE,"新增 组织机构内部门表发生异常");
        }
    }

    /**
     * 根据id删除
     * @param id
     * @return
     */
    @DeleteMapping("/deleteDepartmentInfo/{id}")
    public ApiResultDTO deleteDepartmentInfo(@PathVariable("id") String id){
        try {
            departmentInfoService.deleteDepartmentInfo(id);
            return ApiResultDTO.success(null, "删除成功");
        } catch (Exception e) {
            logger.error("删除 组织机构内部门表发生异常", e);
            return ApiResultDTO.error(ERROR_RSCODE, "删除 组织机构内部门表发生异常");
        }
    }

    /**
     * 修改
     * @param departmentInfo
     * @return
     */
    @PostMapping("/updateDepartmentInfo")
    public ApiResultDTO updateDepartmentInfo(@RequestHeader("tokenid") String tokenid,
                                             @RequestBody DepartmentInfo departmentInfo){
        try {
            UserDTO userDTO = getUser(tokenid);
            //添加操作日志
            OperrateLogs operrateLogs= new OperrateLogs();
            operrateLogs.setMofDivCode(userDTO.getProvince());
            operrateLogs.setTokenId(tokenid);
            operrateLogs.setUserAgencyId(userDTO.getAgency());
            operrateLogs.setUeserName(userDTO.getName());
            operrateLogs.setOperateName("单位信息编辑--内部机构维护--修改科室");
            operrateLogs.setAgencyId(departmentInfo.getAgencyId());
            iOperrateLogsService.saveOperrateLogs(operrateLogs);

            String restlt=departmentInfoService.updateDepartmentInfo(departmentInfo);
            return ApiResultDTO.success(restlt, "修改成功");
        } catch (Exception e) {
            logger.error("修改 组织机构内部门表发生异常", e);
            return ApiResultDTO.error(ERROR_RSCODE, "修改 组织机构内部门表发生异常");
        }
    }

    /**
     * 分页查询
     * @param page
     * @param limit
     * @return
     */
    @GetMapping("/queryDepartmentInfoPage")
    public ApiResultDTO queryDepartmentInfoPage(@RequestHeader("tokenid") String tokenid,
                                                @RequestParam(value = "page") String page,
                                                @RequestParam(value = "limit") String limit,
                                                @RequestParam(value = "agencyId") String agencyId,
                                                @RequestParam(value = "departmentId", required = false) String departmentId
                                                ){
        try {
            UserDTO userDTO = getUser(tokenid);
            List<String> childrenId = departmentInfoService.getChildrenId(departmentId,agencyId,userDTO.getProvince());
            Map<String, Object> queryParam = new HashMap<>(1);
            queryParam.put("agencyId", agencyId);
            queryParam.put("departmentId", departmentId);
            queryParam.put("mofDivCode", userDTO.getProvince());
            PaginationDTO paginationDTO = PageUtils.buildPaginationDTOPage(page,limit);
            PageDTO<DepartmentInfo> departmentInfoPageDTO = departmentInfoService.queryDepartmentInfoPage(paginationDTO,queryParam,childrenId);
            return ApiResultDTO.success(departmentInfoPageDTO,null);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return ApiResultDTO.error(ERROR_RSCODE, "获取数据异常");
        }
    }

    @GetMapping("/getAgencyDepartmentInfoList")
    public ApiResultDTO getAgencyDepartmentInfoList(@RequestHeader("tokenid") String tokenid,
                                                    @RequestParam(value = "agencyId") String Agencyid){
        try {

            List<Map<String, String>> departmentInfolist = departmentInfoService.getBaseDataSelect(Agencyid);
            return ApiResultDTO.success(departmentInfolist,null);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return ApiResultDTO.error(ERROR_RSCODE, "获取数据异常");
        }
    }

    @GetMapping("/getDepartmentTree")
    public ApiResultDTO getDepartmentTree(@RequestHeader("tokenid") String tokenid,
                                          @RequestParam(value = "agencyId") String agencyId){

        try {
            UserDTO userDTO = getUser(tokenid);
            List<DepartmentInfo> department = departmentInfoService.getAllDepartment(agencyId,userDTO.getProvince());
            List<Map<String, Object>> topTree = new ArrayList<>();
            List<Map<String, Object>> tree = getAgencyDepartmentTree(department, "0");
            Map<String, Object> map = new HashMap<>(1);
            map.put("label", "组织机构");
            map.put("code", "0");
            map.put("children", tree);
            map.put("id","0");
            topTree.add(map);
            return ApiResultDTO.success(topTree);
        } catch (Exception e) {
            logger.error("获取单位树方法异常： " + e.getMessage(), e);
            return ApiResultDTO.error("199999", "获取单位树方法异常");
        }

    }


    public List<Map<String, Object>> getAgencyDepartmentTree(List<DepartmentInfo> list,String guid){

        List<Map<String, Object>> resultTree = new ArrayList<>();
        if(list!=null&&list.size()>0){
            for (int i = 0; i < list.size(); i++) {
                DepartmentInfo departmentInfo=list.get(i);
                 if("0".equals(guid)&&"1".equals(departmentInfo.getLevelNo())){
                     List<Map<String, Object>> childrenList = new ArrayList<>();
                     Map<String, Object> map = new HashMap<>();
                     map.put("code",departmentInfo.getDeptCode());
                     map.put("label",departmentInfo.getDeptCode() + "-" + departmentInfo.getDeptName());
                     String parGuid=departmentInfo.getId();
                     map.put("id",parGuid);
                     String leaf=String.valueOf(departmentInfo.getIsLeaf());
                     if("0".equals(leaf)){
                         childrenList=getAgencyDepartmentTree(list,parGuid);
                         map.put("children", childrenList);
                     }
                     resultTree.add(map);
                 }else{
                     String superguid=departmentInfo.getParentId();
                     if(guid.equals(superguid)){
                         List<Map<String, Object>> childrenList = new ArrayList<>();
                         Map<String, Object> map = new HashMap<>();
                         map.put("code",departmentInfo.getDeptCode());
                         map.put("label",departmentInfo.getDeptCode() + "-" + departmentInfo.getDeptName());
                         String parGuid=departmentInfo.getId();
                         map.put("id",parGuid);
                         String leaf=String.valueOf(departmentInfo.getIsLeaf());
                         if("0".equals(leaf)){
                             childrenList=getAgencyDepartmentTree(list,parGuid);
                             map.put("children", childrenList);
                         }
                         resultTree.add(map);
                     }
                 }
            }
        }
        return resultTree;
    }

    @GetMapping("/getDepartmentOptions")
    public ApiResultDTO getDepartmentOptions(@RequestHeader("tokenid") String tokenid,
                                             @RequestParam(value = "agencyId") String agencyId){
        try {
            UserDTO userDTO = getUser(tokenid);
            List<DepartmentInfo> list = departmentInfoService.getAllDepartment(agencyId,userDTO.getProvince());
            List<Map<String, Object>> Options = getAgencyDepartmentOptions(list,"0");
            return ApiResultDTO.success(Options);
        } catch (Exception e) {
            logger.error("获取单位级联方法异常： " + e.getMessage(), e);
            return ApiResultDTO.error("199999", "获取单位级联方法异常");
        }
    }

    public List<Map<String, Object>> getAgencyDepartmentOptions(List<DepartmentInfo> list,String guid){
        List<Map<String, Object>> Options = new ArrayList<>();
        if(list!=null&&list.size()>0){
            for (int i = 0; i < list.size(); i++) {
                DepartmentInfo departmentInfo=list.get(i);
                if("0".equals(guid) && StringUtils.isEmpty(departmentInfo.getParentId())){
                    List<Map<String, Object>> childrenList = new ArrayList<>();
                    Map<String, Object> map = new HashMap<>();
                    String parGuid=departmentInfo.getId();
                    map.put("value",parGuid);
                    map.put("label",departmentInfo.getDeptCode() + "-" + departmentInfo.getDeptName());

                    String leaf=String.valueOf(departmentInfo.getIsLeaf());
                    if("0".equals(leaf)){
                        childrenList=getAgencyDepartmentTree(list,parGuid);
                        map.put("children", childrenList);
                    }
                    Options.add(map);
                }else{
                    String superguid=departmentInfo.getParentId();
                    if(guid.equals(superguid)){
                        List<Map<String, Object>> childrenList = new ArrayList<>();
                        Map<String, Object> map = new HashMap<>();
                        String parGuid=departmentInfo.getId();
                        map.put("value",parGuid);
                        map.put("label",departmentInfo.getDeptName());

                        String leaf=String.valueOf(departmentInfo.getIsLeaf());
                        if("0".equals(leaf)){
                            childrenList=getAgencyDepartmentTree(list,parGuid);
                            map.put("children", childrenList);
                        }
                        Options.add(map);
                    }
                }
            }
        }
        return Options;
    }
}
